<template lang="pug">
    div(class="tree-hole-room tree-hold-top-panel")
        div(class="tree-hole-room-header")
            div(class="tree-hole-room-header__back")
                Icon(type="ios-arrow-back",@click="toBack")
            div(class="tree-hole-room-header__name")
                span {{room.name || '加载中...'}}
            div(class="tree-hole-room-header__power")
                Icon(type="md-more" @click="toRoomInfoView")
        <!--消息循环列表-->
        div(:class="{'tree-hole-room-messages':true, 'tree-hole-room-messages-emoji-visi': emojiVisible}", ref="message_box")
            transition-group( tag="div")
                template(v-for="item in messages")
                    <!--别人发的消息-->
                    template(v-if="item.maskId != mask.id && (item.msgType == 0 || item.msgType == 5)")
                        <!--别人发的文字消息-->
                        div(class="tree-hole-room-messages-receive animated fadeInLeft faster" :key="item.msgId")
                            div(class="tree-hole-room-messages-receive__avatar")
                                img(:src="image2ServerUrl(item.avatar)" @click="showProfile(item)")
                            <!--文本消息-->
                            template(v-if="item.msgType == 0")
                                div(class="tree-hole-room-messages-receive__message-container")
                                    p {{item.maskName}}
                                    div(class="tree-hole-room-messages-receive__message" v-html="item.msg")
                            <!--图片消息-->
                            template(v-if="item.msgType == 5")
                                div(class="tree-hole-room-messages-receive__message-container")
                                    p {{item.maskName}}
                                    div(class="tree-hole-room-messages-receive__message")
                                        Spin(v-if="!item.picLoaded")
                                        img(:class="{'pic-msg-thumb': true, hide: !item.picLoaded}"
                                            :src="image2ServerUrl(item.picUrl)"
                                            @click="showBigPic(item)"
                                            v-lazy="item")

                    <!--我发的消息-->
                    template(v-else-if="item.maskId == mask.id && (item.msgType == 0 || item.msgType == 5)")
                        div(class="tree-hole-room-messages-send animated fadeIn faster" :key="item.msgId")
                            div(class="tree-hole-room-messages-send__avatar")
                                img(:src="image2ServerUrl(item.avatar)")
                                p {{item.maskName}}
                            <!--文本消息-->
                            div(class="tree-hole-room-messages-send__message"  v-html="item.msg" v-if="item.msgType == 0")
                            <!--图片消息-->
                            div(class="tree-hole-room-messages-send__message" v-if="item.msgType == 5")
                                img(:src="item.picUrl" class="pic-msg-thumb" v-if="item.status !== undefined" v-lazy="item")
                                img(:src="image2ServerUrl(item.picUrl)" class="pic-msg-thumb" v-else v-lazy="item")
                            div(class="tree-hole-room-messages-send__actions", v-if="item.status == 'sending'")
                                Spin

                    <!--加入聊天室通知-->
                    template(v-else-if="item.msgType === 1")
                        div(class="tree-hole-room-messages-join animated fadeIn faster" :key="item.msgId")
                            span(style="color:#2db7f5") "{{item.maskName}}"
                            span 加入了聊天室

                    <!--离开聊天室通知-->
                    div(class="tree-hole-room-messages-join animated fadeIn faster",
                        v-else-if="item.msgType === 2", :key="item.msgId")
                        span(style="color:#2db7f5") "{{item.maskName}}"
                        span 离开了聊天室
                    <!--有人被踢出聊天室通知-->
                    div(class="tree-hole-room-messages-join animated fadeIn faster",
                        v-else-if="item.msgType === 6", :key="item.msgId")
                        span(style="color:#2db7f5") "{{item.maskName}}"
                        span 被移出了聊天室

        <!--路由-->
        transition(enter-active-class="animated slideInRight faster" leave-active-class="animated slideOutRight faster")
            router-view

            <!--输入栏-->
        div(class="tree-hole-room-bottom")
            <!--输入栏-->
            div(class="tree-hole-room-form")
                div(class="tree-hole-room-form-attach" @click.stop="tryChooseImage")
                div(class="tree-hole-room-form-input")
                    Richbox(ref="richbox" @focus="emojiVisible=false")
                div(class="tree-hole-room-form-emotion" @click.stop="emotionSwitchClick")
                div(class="tree-hole-room-form-send hold-m-c", @click.prevent="sendText")
                    i(class="tree-hole-room-form-send-icon")
            <!--输入栏-->
            div(class="tree-hole-room-emoji" :style="{height:emojiPickerHeight+'px'}")
                EmojiPicker(v-show="emojiVisible" @emotion-tab="emotionTab" @menu-change="menuChange" ref="emoji")
        confirm(:visible="confirmVisible", content="该聊天室已解散", @click="backHome")
        ActivePanel(:visible="bigPicVisible")
            img(:src="image2ServerUrl(currentPicMsg.picUrl)"
                v-if="currentPicMsg"
                class="tree-hole-room-big-picture"
                @click="closeBigPic")
        Modal(v-model="profileVisible" )
            div(v-if="profileMsgActive" class="profile")
                img(:src="image2ServerUrl(profileMsgActive.avatar)" class="profile-avatar")
                dl
                    dd {{profileMsgActive.maskName}}
            div(slot="footer")
                div(v-if="isAdmin || isCreator")
                    Button(type="error" size="large" long @click="kickout" style="margin-bottom:5px" :loading="profileModalLoading") 踢出聊天
                div
                    Button(type="primary" size="large" long @click="profileVisible = false") 关闭
</template>
<script>
import axios from "@/plugin/axios";
import "animate.css";
import util from "@/lib/util";
import confirm from "@/weui/confirm";

import { Richbox, EmojiPicker } from "awesome-emoji";
import RecieveActionMixins from "./RoomMixins/RecieveAction";
import CheckInMixin from "./RoomMixins/CheckInMixin";
import WxPicMixin from "./RoomMixins/WxPicMixin";
import wxHub from "@/lib/WxHub";
export default {
  components: { confirm, Richbox, EmojiPicker },
  mixins: [RecieveActionMixins, CheckInMixin, WxPicMixin],
  data() {
    return {
      connection: null,
      roomId: null,
      text: "",
      maskId: null,
      focus: false,
      room: {},
      confirmVisible: false,
      messages: [],
      mask: {},
      roomInfoVisible: false,
      emojiPickerHeight: 0, //表情选择框高度
      emojiVisible: false,
      bigPicVisible: false,
      currentPicMsg: null,
      isCreator: false, // 是否是房间创建者
      isAdmin: false, // 是否是管理员
      profileVisible: false,
      profileMsgActive: null,
      profileModalLoading: false
    };
  },
  watch: {
    emojiVisible(val) {
      this.emojiPickerHeight = val ? 200 : 0;
    }
  },

  methods: {
    // 发送文本消息
    sendText() {
      const text = this.$refs.richbox.getContent().trim();
      if (!text) return;
      const data = {
        roomId: this.roomId,
        text,
        maskId: this.mask.id
      };
      const options = { url: "chatRoom/room/sendText", method: "post", data };

      const msg = {
        msgId: util.newId(4),
        roomId: this.roomId,
        maskId: this.mask.id,
        maskName: this.mask.nickname,
        avatar: this.mask.avatar.url,
        msgType: 0,
        msg: this.$refs.richbox.content2HtmlContent(text),
        status: "sending"
      };
      this.messages.push(msg);
      const index = this.messages.length;
      axios(options)
        .then(() => {
          this.messages[index - 1].status = null;
        })
        .catch(err => {
          this.$Message.error(err.message);
          if (err.code == -2) this.$router.back();
        });
      this.text = "";
      if (!this.emojiVisible) this.$refs.richbox.focus();
      this.$refs.richbox.setContent("");
      return false;
    },
    joinRoom() {
      const data = {
        roomId: this.roomId,
        msgId: util.newId()
      };
      const options = { url: "chatRoom/room/join", method: "post", data };
      const vm = this;
      axios(options)
        .then(response => {
          if (!response.room) return; // todo: 房间不存在

          vm.room = response.room;
          vm.mask = response.mask;
          vm.isAdmin = response.isAdmin;
          vm.isCreator = response.isCreator;
          util.title(vm.room.name);
          wxHub.start().then(wx => {
            const path = vm.$router.resolve(vm.$route.name);
            let fullUrl =
              window.location.origin + "/" + path.href + "/" + vm.room.id;
            fullUrl = fullUrl + "?a=1";

            wx.updateAppMessageShareData({
              title: vm.room.name + "-树洞",
              desc: "向你分享了聊天室",
              link: fullUrl,
              imgUrl:
                "https://img.yzcdn.cn/upload_files/2018/12/04/Fs2MKthTfft2XLKQbxIP98sTO5VH.jpg"
            });
          });
        })
        .catch(err => {
          if (err.code == 404) this.confirmVisible = true;
          // todo: show tips
        });
    },
    toBack() {
      history.back();
    },
    emotionSwitchClick() {
      this.emojiVisible = !this.emojiVisible;
    },
    emotionTab(emotion, emotionEl) {
      this.$refs.richbox.insertElement(emotionEl);
    },
    menuChange() {},
    toRoomInfoView() {
      this.emojiVisible = false; // 关闭表情
      this.$router.push({
        name: "hall-room-info",
        params: { id: this.roomId }
      });
    },
    backHome(val) {
      switch (val) {
        default:
          location.href =
            location.origin + `${location.pathname}/#/`.replace("//", "");
          break;
      }
    },
    // 选择图片
    tryChooseImage() {
      // todo: 判断是不是微信手机端
      const vm = this;
      this.chooseImage().then(localIds => {
        vm.uploadImage(localIds[0]).then(serverId => {
          vm.sendPicMsg(serverId, localIds[0]);
        });
      });
    },
    // 发送图片消息
    sendPicMsg(serverId, localId) {
      const data = { roomId: this.roomId, serverId };
      const options = { url: "chatroom/room/sendPic", method: "post", data };
      const message = {
        msgId: util.newId(4),
        maskId: this.mask.id,
        maskName: this.mask.maskName,
        avatar: this.mask.avatar.url,
        msgType: 5,
        picUrl: localId,
        status: "sending"
      };

      axios(options)
        .then(res => {
          message.status = "ok"; // 发送成功
        })
        .catch(err => {
          alert(err.message);
          message.status = "fail"; // 发送失败
          this.$Message.error(err.message);
          if (err.code == -2) this.$router.back(); // 被移除聊天室
        });
      // 滚动到聊天窗口底部
      const isScrollToBottom = this.isScrollToBottom();
      this.messages.push(message);
      if (isScrollToBottom) this.scrollToBottom();
    },
    showBigPic(picMsg) {
      this.currentPicMsg = picMsg;
      this.bigPicVisible = true;
    },
    closeBigPic() {
      this.bigPicVisible = false;
    },
    showProfile(msg) {
      this.profileVisible = true;
      this.profileMsgActive = msg;
    },
    kickout() {
      const data = {
        roomId: this.roomId,
        maskId: this.profileMsgActive.maskId
      };
      const options = { url: "chatroom/room/kickout", method: "post", data };
      this.profileModalLoading = true;

      axios(options)
        .then(() => {
          this.profileVisible = false;
        })
        .catch(error => {
          this.$Message.error(error.message);
        })
        .then(() => {
          this.profileModalLoading = false;
        });
    }
  },
  created() {
    this.roomId = this.$route.params.id;
    this.joinRoom();
  },
  mounted() {
    if (util.isWeixin()) {
      const app = document.getElementsByClassName("tree-hole-room-messages")[0];
      util.wxH5DragDownForbidden(app);
    }
  },
  directives: {
    focus: {
      inserted: function(el) {}
    },
    lazy: {
      inserted: function(el, binding, vnode) {
        el.onload = function() {
          // el.classList.remove('hide')
          binding.value.picLoaded = true; // 图片设置为已加载完成
          vnode.context.$set(vnode.context.messages, vnode.context.messages);

          // 滚动到聊天窗口底部
          const isScrollToBottom = vnode.context.isScrollToBottom();
          if (isScrollToBottom) vnode.context.scrollToBottom();
        };
      }
    }
  }
};
</script>
<style scoped lang="less">
@import "./RoomMixins/style";

.profile {
  text-align: center;
}

.profile-avatar {
  max-width: 40px;
  border-radius: 50%;
}
</style>
<style>
.tree-hole-room-big-picture {
  max-width: 320px;
  margin: 0 auto;
}
</style>
<style lang="less">

.emoji-picker-parent div.awesome-richbox {
  @height: 26px;
  max-height:  @height * 3;
  min-height:  @height;
  line-height:  @height;
  padding: 0px 5px;

  overflow: scroll;
}
</style>